package org.jypj.dev.controller;

import org.jypj.dev.model.CodeData;
import org.jypj.dev.model.User;
import org.jypj.dev.service.ICodeDataService;
import org.jypj.dev.service.IUserService;
import org.jypj.dev.util.*;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * User控制器
 *
 * @author ChenYu
 */
@Controller
@RequestMapping("userController")
public class UserController {

    @Resource
    private IUserService userService;

    @Resource
    private ICodeDataService codeDataService;

    @RequestMapping(value = "toUserList.action")
    public String toUserList(HttpServletRequest request) {
        List<CodeData> codeDatas = codeDataService.selectAllByCode("jsgl");
        request.setAttribute("codeDatas", codeDatas);
        return "back/sys/user_main";
    }

    @RequestMapping(value = "toModifyPwd.action")
    public String toModifyPwd() {

        return "back/sys/pwd_setting";
    }

    /**
     * 跳转到用户表单页面
     *
     * @return
     */
    @RequestMapping(value = "toUserForm.action")
    public String toUserForm(String id, HttpServletRequest request) {
        List<CodeData> codeDatas = codeDataService.selectAllByCode("jsgl");
        request.setAttribute("jss", codeDatas);
        List<CodeData> codeDatas2 = codeDataService.selectAllByCode("bmgl");
        request.setAttribute("bms", codeDatas2);
        List<CodeData> codeDatas3 = codeDataService.selectAllByCode("cxgl");
        if (StringUtil.isNotEmpty(id)) {
            User user = userService.selectUserById(id);
            // 查询所有车型
            for (CodeData cd : codeDatas3) {
                if (user.getTrainType() != null && user.getTrainType().contains(cd.getItemValue())) {
                    cd.setIsCheck("true");
                } else {
                    cd.setIsCheck("false");
                }
            }
            request.setAttribute("formUser", user);
        } else {
            request.setAttribute("formUser", new User());
        }
        request.setAttribute("tts", codeDatas3);
        return "back/sys/user_form";
    }

    /**
     * 查询所有数据接口
     *
     * @return code =-1 表示有异常 code=-2 表示没有数据 datas 菜单数据
     */
    @RequestMapping("selectAllUser.action")
    @ResponseBody
    public Map<String, Object> selectAllUser() {
        Map<String, Object> map = new HashMap<>();
        int code = 0;
        try {
            List<User> users = userService.selectAllByMap(new HashMap<String, Object>());
            if (users.size() == 0) {
                code = -2;
            }
            map.put("datas", users);
        } catch (Exception e) {
            code = -1;
        }
        map.put("code", code);
        return map;
    }

    /**
     * 分页查询用户
     *
     * @param page
     * @return
     */
    @RequestMapping("selectOnePage.action")
    @ResponseBody
    public Page selectOnePage(String searchKey, String roleType, Page page) {
        Map<String, Object> map = new HashMap<>();
        map.put("searchKey", searchKey);
        map.put("roleType", roleType);
        page = userService.selectOnePageByMap(page, map);
        return page;

    }

    /**
     * 查询下拉框数据
     *
     * @return
     */
    @RequestMapping("selectDataMap.action")
    @ResponseBody
    public Map<String, Object> selectDataMap() {
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> dataMap = new HashMap<>();
        Map<String, Object> queryMap = new HashMap<>();
        int code = 0;
        try {
            queryMap.put("code", "bmgl");
            List<CodeData> deps = codeDataService.selectAllByMap(queryMap);
            queryMap.put("code", "jsgl");
            List<CodeData> roleTypes = codeDataService.selectAllByMap(queryMap);
            queryMap.put("code", "gzgl");
            List<CodeData> workTypes = codeDataService.selectAllByMap(queryMap);
            dataMap.put("deps", deps);
            dataMap.put("roleTypes", roleTypes);
            dataMap.put("workTypes", workTypes);
        } catch (Exception e) {
            code = -1;
        }
        map.put("dataMap", dataMap);
        map.put("code", code);
        return map;
    }

    /**
     * 查询下拉框数据
     *
     * @return
     */
    @RequestMapping("saveOrUpdate.action")
    @ResponseBody
    public Map<String, Object> saveOrUpdate(User user) {
        Map<String, Object> map = new HashMap<>();
        String todayString = DateUtils.getTodayString("yyyy-MM-dd HH:mm:ss");
        int code = 0;
        try {
            Map<String, String> ps = PinYinUtil.changeChinese2Pinyin(user.getUsername());
            user.setFullPinYin(ps.get("f"));
            user.setSimplePinYin(ps.get("s"));
            Map<String, String> trainTypeNames = user.getTrainTypeNames();
            String trainTypes = "";
            for (String trainType : trainTypeNames.keySet()) {
                trainTypes = trainTypes + trainType + ",";
            }
            user.setTrainType(trainTypes);
            if (StringUtil.isNotEmpty(user.getId())) {
                // 更新
                user.setModifyDate(todayString);
                userService.updateUserByField(user);
            } else {
                // 保存
                user.setCreateDate(todayString);
                user.setModifyDate(todayString);
                user.setPassword("000");
                user.setPasswordMd5("c6f057b86584942e415435ffb1fa93d4");
                user.setToken(MD5Utils.md5Encrypt(user.getUserNum() + user.getPassword()));
                userService.saveUser(user);
            }
        } catch (DuplicateKeyException e) {
            code = -2;
        } catch (Exception e) {
            e.printStackTrace();
            code = -1;
        }
        map.put("code", code);
        return map;
    }

    /**
     * 删除用户
     *
     * @return
     */
    @RequestMapping("deleteUser.action")
    @ResponseBody
    public Map<String, Object> deleteUser(String id) {
        Map<String, Object> map = new HashMap<>();
        int code = 0;
        try {
            userService.deleteUserById(id);
        } catch (Exception e) {
            e.printStackTrace();
            code = -1;
        }
        map.put("code", code);
        return map;
    }

    /**
     * 修改密码
     *
     * @param password
     * @param newPwd
     * @return
     */
    @RequestMapping("modifyPassword.action")
    @ResponseBody
    public Map<String, Object> modifyPassword(String password, String newPwd, HttpSession session) {
        Map<String, Object> map = new HashMap<>();
        int code = 0;
        User user = (User) session.getAttribute("user");
        try {
            if (user != null) {
                if (!password.equals(user.getPassword())) {
                    code = -2;//原始密码不正确
                } else if (password.equals(newPwd)) {
                    code = -3;//新密码和旧密码相同
                } else {
                    user.setPassword(newPwd);
                    user.setPasswordMd5(MD5Utils.md5Encrypt(newPwd));
                    user.setToken(MD5Utils.md5Encrypt(user.getUserNum() + newPwd));
                    userService.updateUser(user);
                }
            } else {
                code = -4;//登录超时
            }
        } catch (Exception e) {
            e.printStackTrace();
            code = -1;
        }
        map.put("code", code);
        return map;
    }

}